package com.wenjh.jdmzt.android.activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.os.MessageQueue.IdleHandler;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;

import com.umeng.analytics.MobclickAgent;
import com.wenjh.jdmzt.MApplication;
import com.wenjh.jdmzt.R;
import com.wenjh.jdmzt.android.view.ActionBar;
import com.wenjh.jdmzt.android.view.ActionButton;
import com.wenjh.jdmzt.util.Log4Android;
import com.wenjh.jdmzt.util.StringUtils;
import com.wenjh.jdmzt.util.Toaster;

/**
 * 所有Activity的基类
 */
public abstract class BaseActivity extends FragmentActivity {
	protected Log4Android log = new Log4Android(getClass().getSimpleName());
	private Map<Integer, WeakReference<View>> viewCache = new HashMap<Integer, WeakReference<View>>();
	
	private boolean foreground = false;
	private boolean initialized = false;
	
	private ActionBar headerLayout = null;
	
	@SuppressWarnings("rawtypes")
	private List<AsyncTask> asyncTasks = null;
	
	private Dialog dialog = null;
	
	public void toast(int resId) {
		if(isForeground()) {
			Toaster.show(resId, Toaster.LENGTH_LONG);
		}
	}
	
	public void toast(CharSequence message) {
		if(isForeground()) {
			Toaster.show(message, Toaster.LENGTH_LONG);
		}
	}
	
	public void toastInvalidate(CharSequence message) {
		if(isForeground()) {
			Toaster.showInvalidate(message, Toaster.LENGTH_LONG);
		}
	}
	
	public void toastInvalidate(int resId) {
		if(isForeground()) {
			Toaster.showInvalidate(resId, Toaster.LENGTH_LONG);
		}
	}
	
	public ActionBar getHeaderBar() {
		if(headerLayout == null) {
			headerLayout = (ActionBar) findViewById(R.id.layout_header);
		}
		
		return headerLayout;
	}
	
	public void addHeaderButton(ActionButton headerButton, OnClickListener listener) {
		getHeaderBar().addButton(headerButton, listener);
	}
	
	public void addHeaderButton(ActionButton headerButton) {
		addHeaderButton(headerButton, null);
	}
	
	/**
	 * 设置Activity的标题。如果 {@link #getHeaderBar()}的结果不为空，标题将显示在HeaderBar上。
	 * 设置的结果可以通过 {@link #getTitle()} 获得
	 */
	public void setTitle(CharSequence title) {
		if(getHeaderBar() != null) {
			getHeaderBar().setTitleText(title);
		}

		super.setTitle(title);
	}
	
	@Override
	public void setTitle(int titleId) {
		
		if(getHeaderBar() != null) {
			getHeaderBar().setTitleText(titleId);
		}
		
		super.setTitle(titleId);
	}
	
	public void setSubTitle(CharSequence title) {
		if(getHeaderBar() != null) {
			getHeaderBar().setSubTitleText(title);
		}
	}
	
	/**
	 * <pre>
	 * 显示对话框。
	 * 调用此方法表示将 Dialog 交予 Activity 管理。
	 * BaseActivity 认为当前 Activity 仅同时存在一个 Diloag，因此调用这个方法会自动关闭之前在前台的 Dialog。
	 * </pre>
	 * 
	 * @param dialog
	 */
	public synchronized void showDialog(Dialog dialog) {
		closeDialog();
		this.dialog = dialog;
		if(!isFinishing()) {
			dialog.show();
		}
	}
	
	/**
	 * 关闭当前显示的Dialog。
	 */
	public synchronized void closeDialog() {
		if(dialog != null && dialog.isShowing() && !isFinishing()) {
			dialog.dismiss();
			dialog = null;
		}
	}
	
	/**
	 * 此界面是否在前台
	 */
	public boolean isForeground() {
		return foreground;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initialized = false;
		asyncTasks = new ArrayList<AsyncTask>();
		
		/*Looper.myQueue().addIdleHandler(new IdleHandler() {
			@Override
			public boolean queueIdle() {
				onInitialize();
				initialized = true;
				return false;
			}
		});*/
		
		/*getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<Object>() {
			@Override
			public Loader<Object> onCreateLoader(int arg0, Bundle arg1) {
				AsyncTaskLoader<Object> loader = new AsyncTaskLoader<Object>(getApplicationContext()) {
					@Override
					public Object loadInBackground() {
						return new Object();
					}
				};
				return loader;
			}

			@Override
			public void onLoadFinished(Loader<Object> arg0, Object arg1) {
//				onInitialize();
//				initialized = true;
			}

			@Override
			public void onLoaderReset(Loader<Object> arg0) {
				
			}
		}).forceLoad();*/
		
		
		/*new Handler().post(new Runnable() {
			@Override
			public void run() {
				new Handler().post(new Runnable() {
					@Override
					public void run() {
						log.i("onInitialize~~~~~~~~~~~~~~");
						onInitialize();
						initialized = true;
					}
				});
			}
		});*/
	}
	
	@SuppressWarnings("rawtypes")
	public AsyncTask putAsyncTask(AsyncTask asyncTask) {
		asyncTasks.add(asyncTask);
		return asyncTask;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void executeAsyncTask(AsyncTask asyncTask) {
		putAsyncTask(asyncTask).execute();
	}
	
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		if(getHeaderBar() != null && StringUtils.isEmpty(getHeaderBar().getTitleText())) {
			getHeaderBar().setTitleText(getTitle());
		}
		
		Looper.myQueue().addIdleHandler(new IdleHandler() {
			@Override
			public boolean queueIdle() {
				onInitialize();
				initialized = true;
				return false;
			}
		});
		
		/*new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				onInitialize();
				initialized = true;
			}
		}, 100);*/
	}
	
	protected void onInitialize() {
	}
	
	protected final boolean isInitialized() {
		return initialized;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		for (@SuppressWarnings("rawtypes") AsyncTask task : asyncTasks) {
			if(task !=null && !task.isCancelled()) {
				task.cancel(true);
			}
		}
	}
	
	@Override
	public View findViewById(int id) {
		View findView = viewCache.get(id) != null ? viewCache.get(id).get() : null;
		if(findView == null) {
			findView = super.findViewById(id);
			viewCache.put(id, new WeakReference<View>(findView));
		}
		return findView;
	}
	
	@SuppressWarnings("unchecked")
	public <T extends View> T findViewById(int id, T t) {
		return (T) findViewById(id);
	}
	
	private int resumCount = 0;
	@Override
	protected void onResume() {
		super.onResume();
		foreground = true;
		ActivityHandler.onActivityResume();
		MobclickAgent.onResume(this);
		resumCount++;
		if(resumCount == 1) {
			onFristResume();
		} else if(resumCount == 2) {
			onSecondResume();
		}
	}
	
	protected void onFristResume() {
		
	}
	
	protected void onSecondResume() {
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		foreground = false;
		ActivityHandler.onActivityPause();
	}
	
	protected MApplication getApp() {
		return (MApplication) getApplication();
	}
	
	/**
	 * 初始化绑定事件方法。在这个方法里面绑定事件Listener。便于阅读以及管理。
	 * <p>
	 *   例：
	 *     chatView.setOnItemClickListener(l);
	 * </p>
	 */
	protected abstract void initEvents();
	
	/**
	 * 初始化View方法。
	 * 通常在这个方法里面从布局文件里findViewById加载控件或者addView等等。便于阅读以及管理。
	 * 大多数情况下，要保证这个方法在{@link com.immomo.momo.android.activity.BaseAccountActivity#initEvent()}之前调用。但是没有使用机制强制规定。
	 * <p>
	 *   例：
	 *     chatView = (ListView)findViewById(R.id.listview);
	 * </p>
	 */
	protected abstract void initViews();
	
	/**
	 * 初始化data方法。
	 * 通常在这个方法里面初始化一些数据,可以异步加载等相关操作。便于阅读以及管理。
	 * 大多数情况下，要保证这个方法在{@link com.immomo.momo.android.activity.BaseAccountActivity#initEvent()}之前调用。但是没有使用机制强制规定。
	 * <p>
	 *   例：
	 *     datalist = new GetDataTask().execute();
	 * </p>
	 */
	protected void initData() {
	}
	
	/**
	 * requestCode 不能大于65535
	 */
	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		super.startActivityForResult(intent, requestCode);
	}
	
	public void back(View v) {
		finish();
	}
}
